/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;


import Conexao.ConsultaBD;
import Entidade.Agendamento;
import Entidade.Sala;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Andre
 */
public class cadAgendamentoServlet extends HttpServlet {

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        RequestDispatcher rd;
        
        Agendamento agenda = new Agendamento();
                    
        try {
            
            
            String eventoS = request.getParameter("evento");
            String solicitanteNome = request.getParameter("solicitante_nome");
            String data1 = request.getParameter("solicitante_nome");
            String data2 = request.getParameter("data2");
            String solicitanteEmail = request.getParameter("solicitante_email");
            
            if(!eventoS.equals("") || !solicitanteEmail.equals("") || !solicitanteNome.equals("") || !data1.equals("") || !data2.equals("")){            
            
            Date data = new Date();
            
            java.sql.Date d1, d2;
            String dt;

            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

            //captura data1
            dt = request.getParameter("data1");
            d1 = new java.sql.Date(format.parse(dt).getTime());
            //captura data2
            dt = request.getParameter("data2");
            d2 = new java.sql.Date(format.parse(dt).getTime());
            //captura a hora
            long h1 = Integer.valueOf(request.getParameter("hora1"));
            long h2 = Integer.valueOf(request.getParameter("hora2"));
            
            
            if(d1.getDate() < data.getDate() || d2.getDate() < data.getDate())
            {
                rd = request.getRequestDispatcher("cadastroagendamento.jsp?item=agendamento");
                rd.include(request, response);
                String erro = "<script>"
                        + "alert('Erro: Verifique a data do agendamento.');"
                        + "</script>";
                        
                out.print(erro);
            }
            else if(d1.getTime() != d2.getTime())
            {
                rd = request.getRequestDispatcher("cadastroagendamento.jsp?item=agendamento");
                rd.include(request, response);
                String erro = "<script>"
                        + "alert('Erro: Verifique a data do agendamento. Dever ser datas iguais.');"
                        + "</script>";
                        
                out.print(erro);
            }
            else{
            
            //pega a sala << CODIGO DEVE SER MODIFICADO NA TELA DE CADASTRO DE AGENDAMENTO>>
            Long sala = Long.valueOf(request.getParameter("cod_sala"));         
            
            String obs = request.getParameter("observacao");
            String evento = request.getParameter("evento");

            if ((d1.getTime() <= d2.getTime()) && h1 < h2) {

               String sql = "select a.id, a.evento, a.observacao, a.solicitante_nome, a.solicitante_email, a.data_fim, a.data_inicio, a.hora_inicio, a.hora_fim from Agendamento as a where " +
                        " ((data_inicio >='" + d1 + "' and data_fim <='" + d2 + "') " +
                        " and ((hora_inicio >= " + h1 + " and hora_fim <= " + h2 + ") or " +
                        "      (hora_inicio <= " + h1 +  " and hora_fim <= " + h2 + " and hora_fim > " + h1 + ") or " +
                        "      (hora_inicio <= " + h1 + " and hora_fim >= " + h2 + ") or " +
                        "      (hora_inicio >= " + h1 + " and hora_inicio <= " + h2 + " and hora_fim >= " + h2 + "))" +
                        " and sala = " + sala + ")";              
            
                
                    
                    List<Object> agendamentoObjt = ConsultaBD.ListaSQL(sql);  
              
                if(agendamentoObjt.isEmpty()) {
                    
                    agenda.setSala((Sala) ConsultaBD.SelecionarFrom("Sala where id=" + sala.toString()));
                    agenda.setData_inicio(d1);
                    agenda.setData_fim(d2);
                    agenda.setHora_inicio(h1);
                    agenda.setHora_fim(h2);
                    agenda.setSolicitante_nome(request.getParameter("solicitante_nome"));
                    agenda.setSolicitante_email(request.getParameter("solicitante_email"));
                    agenda.setEvento(evento);
                    agenda.setObservacao(obs);
                    
                    Random r = new Random();  
                    int i = r.nextInt(1000 * 144); 
                    
                    agenda.setAutenticador(String.valueOf(i));
                    
                    try {
                        
                        agenda.Salvar(agenda);
                        
                    } catch (Exception e) {
                    }
                    
                    
                } 
                else {
                rd = request.getRequestDispatcher("cadastroagendamento.jsp?item=agendamento");
                rd.include(request, response); 
                String erro = "<script>"
                        + "alert('Erro: Já existe alocação de sala para data/horário desejado.');"
                        + "</script>";
                        
                out.print(erro);
                
               }
                
            }else {

                rd = request.getRequestDispatcher("cadastroagendamento.jsp?item=agendamento");
                rd.include(request, response);    
                String erro = "<script>"
                        + "alert('Erro: Data/Hora inválidas.');"
                        + "</script>";
                        
                out.print(erro);
                }

               }   
            
            }else {
                
                rd = request.getRequestDispatcher("cadastroagendamento.jsp?item=agendamento");
                rd.include(request, response);    
                String erro = "<script>"
                        + "alert('Erro: Informe os campos obrigatórios!');"
                        + "</script>";
                        
                out.print(erro);
            }

              }
            finally {
            
            if(agenda.getId() != null)
            {
                rd = request.getRequestDispatcher("cadastroagendamento.jsp?item=agendamentoequipamento&id_agenda=" + agenda.getId().toString());
                rd.include(request, response);
            }
            else{
                //rd = request.getRequestDispatcher("cadastroagendamento.jsp?item=agendamento");
                //rd.include(request, response);  
            }
            out.close();
            
        }
    }


    // <editor-fold defaultstate="collapsed" desc="Métodos HttpServlet. Clique no sinal de + à esquerda para editar o código.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(cadAgendamentoServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(cadAgendamentoServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(cadAgendamentoServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(cadAgendamentoServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


